package avicit.bdp.dms.prm.rest;

import avicit.bdp.common.dto.CommonVO;
import avicit.bdp.common.service.dto.CommonTypeDTO;
import avicit.bdp.dms.prm.dto.DataElement;
import avicit.bdp.dms.prm.dto.DataElementDTO;
import avicit.bdp.dms.prm.service.DataElementService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据元管理REST接口
 */
@RestController
@Api(tags = "数据元管理", description = "bdp_prm_data_element")
@RequestMapping("/api/bdp/dms/prm/dataElement")
public class DataElementRest {

    @Autowired
    private DataElementService dataElementService;
    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 新增数据元对象
     */
    @ApiOperation(value = "新增数据元对象")
    @PostMapping("/insertDataElement")
    public ResponseMsg<String> insertDataElement(@RequestBody DataElementDTO dataElement) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        dataElement.setOrgIdentity(ThreadContextHelper.getOrgId());
        responseMsg.setResponseBody(dataElementService.insertDataElement(dataElement));
        return responseMsg;
    }

    /**
     * 判断英文名和编码是否重复
     */
    @ApiOperation(value = "判断英文名和编码是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "英文名/code", name = "value", dataType = "String"),
            @ApiImplicitParam(value = "类型（name/code）", name = "type", dataType = "String")
    })
    @GetMapping("/isSameName")
    public ResponseMsg<Boolean> isSameName(@RequestParam(required = false) String id, @RequestParam String value,
                                           @RequestParam String type) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        Boolean flag = dataElementService.isSameName(id, value, type);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    /**
     * 修改数据元
     */
    @ApiOperation(value = "修改数据元对象")
    @PostMapping("/updateDataElement")
    public ResponseMsg<String> updateDataElement(@RequestBody DataElementDTO dataElement) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        dataElementService.updateDataElement(dataElement);
        return responseMsg;
    }

    /**
     * 删除数据元
     */
    @ApiOperation(value = "刪除数据元对象")
    @PostMapping("/deleteDataElement")
    public ResponseMsg<Integer> deleteDataElement(@RequestBody CommonVO commonVO) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        String id = commonVO.getId();
        dataElementService.deleteDataElement(id);
        return responseMsg;
    }

    /**
     * 修改数据元状态
     */
    @ApiOperation(value = "修改数据元状态")
    @PostMapping("/updateStatus")
    public ResponseMsg<String> updateStatus(@RequestBody CommonVO commonVO) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String id = commonVO.getId();
        Integer status = commonVO.getStatus();
        dataElementService.updateStatus(id, status);
        return responseMsg;
    }

    /**
     * 查询数据元列表
     */
    @ApiOperation(value = "查询数据元列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "分类id", name = "typeId", dataType = "String", required = true),
            @ApiImplicitParam(value = "查询关键字", name = "keyWords", dataType = "String"),
            @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int"),
            @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int")
    })
    @GetMapping("/getListForElement")
    public ResponseMsg<QueryRespBean<DataElementDTO>> getListForElement(
            @RequestParam String typeId,
            @RequestParam(required = false) String keyWords,
            @RequestParam(defaultValue = "1", required = false) Integer pageNo,
            @RequestParam(defaultValue = "10", required = false) Integer pageSize) {

        ResponseMsg<QueryRespBean<DataElementDTO>> responseMsg = new ResponseMsg<>();
        QueryRespBean<DataElementDTO> result = dataElementService.getListForElement(typeId, keyWords, pageNo, pageSize);
        valueConvert(result.getResult());
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    @ApiOperation(value = "查询数据元")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "查询关键字", name = "keyWords", dataType = "String"),
            @ApiImplicitParam(value = "数据空间id", name = "projectId", dataType = "String")
    })
    @GetMapping("/getDataElementList")
    public ResponseMsg<List<CommonTypeDTO>> getDataElementList(
            @RequestParam(required = false) String keyWords,
            @RequestParam(required = false) String projectId) throws Exception{
        ResponseMsg<List<CommonTypeDTO>> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(dataElementService.getDataElementList(projectId, keyWords));
        return responseMsg;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     */
    private void valueConvert(List<DataElementDTO> dataElementList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (DataElementDTO dataElementDTO : dataElementList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dataElementDTO.getCreatedBy());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (DataElementDTO dataElementDTO : dataElementList) {
                dataElementDTO.setCreateUser(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                        dataElementDTO.getCreatedBy()));
            }
        }
    }

    /**
     * 下载数据元模板
     */
    @ApiOperation(value = "下载数据元模板")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        dataElementService.downloadTemplate(response);
    }

    /**
     * 导出数据元信息
     */
    @ApiOperation(value = "导出数据元")
    @ApiImplicitParam(value = "分类id", name = "typeId", required = true)
    @GetMapping("/export")
    public void export(@RequestParam String typeId, HttpServletResponse response) throws Exception {
        dataElementService.export(typeId, response);
    }

    /**
     *导入数据元信息
     */
    @ApiOperation(value = "导入数据元")
    @PostMapping("/importDataElement")
    public ResponseMsg<List<DataElement>> importDataElement(DataElementDTO dataElementDTO) throws Exception{
        ResponseMsg<List<DataElement>> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(dataElementService.importDataElement(dataElementDTO));
        return responseMsg;
    }

    @ApiOperation(value = "导入飞参参数到数据元")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "分类id", name = "typeId", dataType = "String", required = true),
    })
    @PostMapping("/importParams")
    public ResponseMsg<List<DataElement>> importParams(@RequestBody List<DataElement> paramList,
                                                       @RequestParam String typeId) throws Exception {
        ResponseMsg<List<DataElement>> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(dataElementService.importParams(paramList, typeId));
        return responseMsg;
    }

}
